﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Utility.DataStructure;

namespace Utility.TaskSystem
{
	public class TaskGroup : Task
	{
		LinkedDictionary<Task, int> tasks = new LinkedDictionary<Task, int> ();

		public bool IsLongLive { get; set; } = true;

		public int Count { get { return tasks.Count; } }

		protected override void OnUpdate ()
		{
			foreach (var pair in tasks)
			{
				var task = pair.Key;
				task.Update ();

				if (!task.Alive)
				{
					tasks.Remove (task);
				}
			}

			if ((!IsLongLive) && tasks.Count == 0)
			{
				Done ();
			}
		}

		public Task Add (Task task)
		{
			if (tasks.ContainsKey (task))
			{
				throw new System.Exception ("Repeat task");
			}
			tasks.Add (task, 0);
			return task;
		}

		public Task Add (IEnumerator<Task> co_func)
		{
			CoroutineTask task = new CoroutineTask (co_func);
			return Add (task);
		}

		public bool Remove (Task task)
		{
			return tasks.Remove (task);
		}
	}
}
